class LiteFetionsController < ApplicationController
  before_filter :authorize_for_admin
  layout 'base.html', :only => [:index, :new, :edit]
  
  def index 
    params[:page] = 1 if params[:page].blank?
    params[:order] = 'id' if params[:order].blank?
    params[:by] = 'asc' if params[:by].blank?
    def params.order_by
      "#{self[:order]} #{self[:by]}"
    end
    @fetions = Fetion.paginate(
      :page => params[:page],
      :per_page => 10,
      :order => params.order_by
    )
    
  end
  
  def new
    @fetion = Fetion.new
  end
  
  def create
    @fetion = Fetion.new params[:fetion]
    @fetion.save ? (
      redirect_to lite_fetions_url
    ) : (
      render :new
    )
  end
  
  def edit
    @fetion = Fetion.find(params[:id])
    @fetion.encrypted_password = @fetion.password
  end
  
  def update
    @fetion = Fetion.find(params[:id])
    @fetion.update_attributes(params[:fetion]) ? (
      redirect_to lite_fetions_url
    ) : (
      render :edit
    )
  end
  
  def messages
    params[:type] ||= 'FetionMessage' 
    params[:page] = 1 if params[:page].blank?
    @fetion = Fetion.find(params[:id])    
    @messages = instance_eval(params[:type]).paginate :conditions => [
      'fetion_id = ? and status = ?',
      @fetion.id,
      'unread'
    ],
    :per_page => 20,
    :page => params[:page],
    :order => 'recieved_at desc'
  end
  
  def login_verify
    @fetion = Fetion.find(params[:id])
    @lite_fetion = LiteFetion.new(:id => @fetion.mobile).get(:login_verify)
  end   
  
  def login
    @fetion = Fetion.find(params[:id])
    @lite_fetion = LiteFetion.new(
      :id => @fetion.mobile
    ).get(:login,
      :sessionId => params[:session_id],
      :verifyCode => params[:verify_code],
      :password => @fetion.password
    )
    logger.debug @lite_fetion.to_s
    logger.debug "result is #{@lite_fetion['result']}"
    logger.debug "state is #{@lite_fetion['state']}"
    @lite_fetion['result'] == 'SUCCESS' ? (
      @fetion.status! @lite_fetion['state']
    )  : (
      render :text => @lite_fetion['result'] , :status => 500
    )
  end 
  
  def logout
    @fetion = Fetion.find(params[:id])
    @lite_fetion = LiteFetion.new(
      :id => @fetion.mobile
    ).get(:logout)
    @lite_fetion['result'] == 'SUCCESS' ? (
      @fetion.status! @lite_fetion['state']
    )  : (
      render :text => @lite_fetion['result'] , :status => 500
    )
  end

  def invert_standing
    @fetion = Fetion.find(params[:id])
    @fetion.invert_standing!
  end
end
